package com.example.grpcclient.standalone;

import com.example.grpc.proto.Empty;
import com.example.grpc.proto.UserListResponse;
import com.example.grpc.proto.UserResponse;
import com.example.grpc.proto.UserServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

import java.util.concurrent.TimeUnit;

/**
 * 独立的 gRPC 客户端
 * 可以直接运行此类来测试 gRPC 服务，不依赖 Spring Boot
 */
public class StandaloneGrpcClient {
    
    public static void main(String[] args) throws Exception {
        // 服务端地址和端口
        String host = "localhost";
        int port = 9090;
        
        System.out.println("连接到 gRPC 服务: " + host + ":" + port);
        
        // 创建通道 - 尝试不同的配置
        ManagedChannel channel = ManagedChannelBuilder
                .forAddress(host, port)
                .usePlaintext()
                // 添加额外配置，尝试解决连接问题
                .keepAliveTime(30, TimeUnit.SECONDS)
                .keepAliveTimeout(10, TimeUnit.SECONDS)
                .keepAliveWithoutCalls(true)
                .maxInboundMessageSize(1024 * 1024 * 10) // 10MB
                .build();
        
        try {
            // 创建 stub
            UserServiceGrpc.UserServiceBlockingStub stub = UserServiceGrpc.newBlockingStub(channel);
            
            System.out.println("开始调用 gRPC 服务...");
            
            // 获取所有用户
            Empty request = Empty.newBuilder().build();
            UserListResponse response = stub.listUsers(request);
            
            System.out.println("调用成功！获取到 " + response.getUsersCount() + " 个用户:");
            for (UserResponse user : response.getUsersList()) {
                System.out.println("ID: " + user.getId() + 
                        ", 姓名: " + user.getName() + 
                        ", 年龄: " + user.getAge() + 
                        ", 邮箱: " + user.getEmail());
            }
            
        } catch (Exception e) {
            System.err.println("gRPC 调用失败: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // 关闭通道
            System.out.println("关闭 gRPC 通道...");
            channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
            System.out.println("gRPC 通道已关闭");
        }
    }
} 